package org.gruposp2p.proyectokarma.controller

import grails.converters.JSON
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.Authentication;
import org.gruposp2p.proyectokarma.domain.Vote;
import org.gruposp2p.proyectokarma.domain.Document;
import org.gruposp2p.proyectokarma.domain.Peer;
import org.gruposp2p.proyectokarma.util.VoteResult;

class VoteController {
	
	def springSecurityService
	def voteService

	def save = {
		def userDetails = springSecurityService.principal
		def peer = Peer.get(userDetails.id)
		def voteResult = voteService.processVote(peer, request.JSON)
		if (!voteResult) {
			response.status = 500
			render message(code: 'proyectokarma.vote.systemError')
			return
		}
		if (voteResult.responseStatus != 201) {
			response.status = voteResult.responseStatus
			render 	message(code:voteResult.messageCode)
			return
		}
		response.status = voteResult.responseStatus
		def vote = [id:voteResult.vote.id, documentId:voteResult.vote.document?.id, commentId:voteResult.vote.comment?.id,
			peerId:voteResult.vote.peerFrom?.id, stringValue:voteResult.vote.stringValue, 
			numericValue:voteResult.vote.numericValue ]
		response.setHeader('Location', grailsApplication.config.grails.serverURL + '/votes/' + vote.id)
		render vote as JSON
	}
	
	def show = {
		def voteList = []
		def votesMap = new HashMap()
		if (params.ids?.size() > 0) {
			Vote.getAll(params.ids).collect {vote ->
				if (vote) voteList << vote;
			}
			if (voteList.size() == 0) {
				response.status = 404 //Not Found
				render message(code: 'proyectokarma.vote.voteNotFound', args:[params.ids])
				return
			}
		} else {
			voteList =  Vote.list(params)
			votesMap.numberOfVotesInSystem = Vote.count()
			votesMap.numberOfVotesInRequest = voteList.size()
			votesMap.offset = params.offset
		}
		votesMap.votes = voteList.collect {vote ->
			return [id: vote.id, peerFromId: vote.peerFrom.id, documentId:vote.document?.id, commentId:vote.comment?.id, 
				dateCreated:vote.dateCreated, stringValue:vote.stringValue,  numericValue:vote.numericValue]
		}
		render votesMap as JSON
	}
	
	def update = {}
	
   def delete = {
	   if (params.id) {
		   def vote = Vote.get(params.id)
		   if (vote) vote.delete()
		   else {
			   response.status = 404;
			   render message(code: 'proyectokarma.vote.deleteNotFound', args:[params.id])
			   return
		   }
		   response.status = 200;
		   render message(code: 'proyectokarma.vote.deleteOK', args:[params.id])
		   return
	   } else {
		   response.status = 400  //Bad Request
		   render message(code: 'proyectokarma.vote.deleteBadRequest')
		   return;
	   }
   }
    

}
